package org.theta.framework.web.session;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.core.annotation.Order;
import org.theta.framework.core.utils.DateUtils;

@Order(1)
@WebFilter(filterName = "sessionFilter", urlPatterns = "/")
public class SessionFilter implements Filter {

	private List<String> excludes;

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		HttpServletRequest httpRequest = (HttpServletRequest) request;
		HttpServletResponse httpResponse = (HttpServletResponse) response;
		String servletPath = httpRequest.getServletPath();
		if (excludes != null && excludes.contains(servletPath)) {
			chain.doFilter(httpRequest, httpResponse);
			return;
		}
		HttpSession session = httpRequest.getSession(true);
		UserSession userSession = (UserSession) session.getAttribute(UserSession.USER_SESSION_KEY);
		if (userSession != null) {
			userSession.setLastOptTime(DateUtils.now());
			chain.doFilter(httpRequest, httpResponse);
			return;
		}
		httpResponse.sendError(HttpServletResponse.SC_FORBIDDEN);
	}

	public void setExcludes(String[] excludes) {
		this.excludes = Arrays.asList(excludes);
	}

	@Override
	public void destroy() {
	}

}
